package main

import (
	"fmt"
	"xml"
	"os"
	"bytes"
)

// <current_observation>
//   <display_location> <full>...</full> </display_location>
//   <temp_f>52</temp_f>
//   <temp_c>11</temp_c>
//   <relative_humidity>10%</relative_humidity>
//   <wind_mph>14</wind_mph>
//   <weather>fog</weather>
// </current_observation>

type WUCurrentObservation struct {
	Display_location  WUDisplayLocation
	Temp_f            int
	Temp_c            int
	Relative_humidity string
	Wind_mph          int
	Weather           string
}

type WUDisplayLocation struct {
	Full string
}

func (p *WUCurrentObservation) fetch(location string) os.Error {
	url := fmt.Sprintf("http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query=%s", location)
	b := url_to_buf(url)
	return xml.Unmarshal(bytes.NewBuffer(b), p)
}

// <forecast>
//   <simpleforecast>
//     <forecastday>
//       <date> <weekday>...</weekday> </date>
//       <high> <fahrenheit>64</fahrenheit> <celsius>15</celsius> </high>
//       <low>  <fahrenheit>32</fahrenheit> <celsius>0</celsius>  </low>
//       <conditions>Partly Cloudy</conditions>
//     </forecastday>
//     ...
//   </simpleforecast>
// </forecast>

type WUForecast struct {
	SimpleForecast WUSimpleForecast
}

type WUSimpleForecast struct {
	ForecastDay []WUForecastDay
}

type WUForecastDay struct {
	Date       WUDate
	High       WUTemperaturePair
	Low        WUTemperaturePair
	Conditions string
}

type WUDate struct {
	Weekday string
}

type WUTemperaturePair struct {
	Fahrenheit int
	Celsius    int
}

func (p *WUForecast) fetch(location string) os.Error {
	url := fmt.Sprintf("http://api.wunderground.com/auto/wui/geo/ForecastXML/index.xml?query=%s", location)
	b := url_to_buf(url)
	return xml.Unmarshal(bytes.NewBuffer(b), p)
}

//
//
//

type WUWeather struct {
	WUCurrentObservation
	WUForecast
}

func GetWeather(location string) (*WUWeather, os.Error) {
	signal := make(chan os.Error)
	now := WUCurrentObservation{}
	later := WUForecast{}
	go func() { signal <- now.fetch(location) }()
	go func() { signal <- later.fetch(location) }()
	for i := 0; i < 2; i++ {
		if err := <-signal; err != nil {
			return nil, err
		}
	}
	return &WUWeather{now, later}, nil
}
